using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace ICP_MS;

public class iMassClient
{
	private const int Port = 5001;

	private TcpListener tcpListener = null;

	private TcpClient canClient = null;

	private NetworkStream networkStream = null;

	private StreamReader streamReader = null;

	private StreamWriter streamWriter = null;

	private Thread threadCheckConnected = null;

	private object lockReceive = new object();

	private bool bStop = true;

	public AutoResetEvent processEvent = new AutoResetEvent(initialState: false);

	public static event EventHandler<DataProceeEventArgs> DataEvent;

	public bool Init()
	{
		bStop = false;
		threadCheckConnected = new Thread(ThreadCheckConnect);
		threadCheckConnected.Start();
		return true;
	}

	private void ThreadCheckConnect()
	{
		tcpListener = new TcpListener(IPAddress.Parse("127.0.0.1"), 5001);
		tcpListener.Start();
		while (!bStop)
		{
			try
			{
				if (tcpListener.Pending())
				{
					canClient = tcpListener.AcceptTcpClient();
					networkStream = canClient.GetStream();
					streamReader = new StreamReader(networkStream, Encoding.UTF8);
					streamWriter = new StreamWriter(networkStream, Encoding.UTF8);
					while (!bStop)
					{
						if (networkStream.DataAvailable)
						{
							char[] buf = new char[1024];
							int len = streamReader.Read(buf, 0, buf.Length);
							string buffer = new string(buf);
							processEvent.Reset();
							iMassClient.DataEvent(null, new DataProceeEventArgs(buffer));
							processEvent.WaitOne(900000);
							break;
						}
						Thread.Sleep(100);
					}
				}
				Thread.Sleep(10);
			}
			catch (Exception)
			{
				CloseClient();
			}
			finally
			{
			}
		}
	}

	public void CANAbort()
	{
		Close();
	}

	public void SendDatas(string frame)
	{
		try
		{
			if (streamWriter != null)
			{
				streamWriter.Write(frame);
				streamWriter.Flush();
			}
		}
		catch (Exception ex)
		{
			Log.InsertLog("iMassServer", "发送数据", ex.Message, Severity.Warning);
		}
	}

	private void CloseClient()
	{
		try
		{
			if (streamReader != null)
			{
				streamReader.Close();
			}
			if (streamWriter != null)
			{
				streamWriter.Close();
			}
			if (networkStream != null)
			{
				networkStream.Close();
			}
			if (canClient != null)
			{
				canClient.Close();
			}
		}
		catch (Exception)
		{
		}
		streamReader = null;
		streamWriter = null;
		networkStream = null;
		canClient = null;
		if (tcpListener != null)
		{
			tcpListener.Stop();
			tcpListener = null;
		}
	}

	public void Close()
	{
		bStop = true;
		CloseClient();
		if (threadCheckConnected != null && threadCheckConnected.IsAlive)
		{
			threadCheckConnected.Abort();
		}
	}
}
